using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Mapping.Attributes;
using NHMA = NHibernate.Mapping.Attributes;

namespace SuperMarketManagement.Entity
{

    [Class(Name = "Invoice")]
    public class Invoice
    {
        [Id(1, Name = "AutoId"), Generator(2, Class = "native")]
        public virtual long AutoId { get; set; }
        public virtual string Number { get { return string.Format("INV-{0:000000}", AutoId); } }
        [Property]
        public virtual DateTime CreatedDate { get; set; }

        public virtual double GetTotalPrice()
        {
            return InvoiceItems.Sum(i => i.Price * i.Quantity);
        }

        [Property]
        public virtual double Discount { get; set; }

        [NHMA.List(1, Cascade = "all-delete-orphan")]
        [NHMA.Key(2, Column = "InvoiceAutoId")]
        [NHMA.Index(3, Column = "[Order]")]
        [NHMA.OneToMany(4, ClassType = typeof(InvoiceItem))]
        public virtual IList<InvoiceItem> InvoiceItems { get; set; }

        [ManyToOne(1, Column = "CustomerAutoId")]
        public virtual Customer Customer { get; set; }

        public Invoice()
        {
            InvoiceItems = new List<InvoiceItem>();
        }

        public Invoice(Customer customer, DateTime createdDate, params InvoiceItem[] invoiceItems)
            : this()
        {
            Customer = customer;
            CreatedDate = createdDate;
            foreach (InvoiceItem invoiceItem in invoiceItems)
            {
                AddInvoiceItem(invoiceItem);
            }
        }

        public virtual void AddInvoiceItem(InvoiceItem item)
        {
            item.Invoice = this;
            InvoiceItems.Add(item);
        }

        public virtual void RemoveInvoiceItem(InvoiceItem item)
        {
            item.Invoice = null;
            InvoiceItems.Remove(item);
        }
    }
}